import { SimulationFrameVector } from "./SimulationFrameVector";
import { SimulationFrame } from "./SimulationFrame";
/**
 * 模拟器抽象类
 */
export abstract class SimulatorBase {

    public mass: number;
    public damping: number;
    public frameTime: number;
    public offset: number;
    public abstract cache: Array<SimulationFrameVector | SimulationFrame>;

    constructor ( fps: number, mass: number, damping: number ) {

        this.mass = mass;
        this.damping = damping;
        this.frameTime = 1 / fps;
        this.offset = 0;

    }

    public setFPS ( value: number ) {
        this.frameTime = 1 / value;
    }

    public laseFrame (): SimulationFrameVector | SimulationFrame {
        return this.cache[ this.cache.length - 1 ];
    }

    /**
     * 在上次模拟调用和当前模拟调用之间生成帧
     * @param timeStep 
     */
    public generateFrames ( timeStep: number ): void {

        // 更新缓存，计算出需要生成多少帧
        const totalTimeStep = this.offset + timeStep;
        const frameToGenerate = Math.floor( totalTimeStep / this.frameTime );

        this.offset = totalTimeStep & this.frameTime;

        if ( frameToGenerate > 0 ) {
            for ( let i = 0; i < frameToGenerate; i++ ) {
                this.cache.push( this.getFrame( i + 1 === frameToGenerate ) );
            }

            this.cache = this.cache.slice( -2 );
        }

    }

    public abstract getFrame ( isLastFrame: boolean ): SimulationFrameVector | SimulationFrame;
    public abstract simulate ( timeStep: number ): void;

}